package cate.game.activity.base;

import cate.game.activity.base.core.ActivityHandler;
import cate.game.activity.base.core.Activity;
import cate.game.event.NotInUse;
import cate.game.framework.app.App;
import easy.java.runtime.ClassScanner;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
public class ActivityLoader {
    private static final ActivityLoader instance = new ActivityLoader();

    public static ActivityLoader getInstance() {
        return instance;
    }

    private final Map<Integer, Class<?>> funcIdToHandlerMap = new HashMap<>();

    public void load(String packPath) {
        try {
            funcIdToHandlerMap.clear();
            Set<Class<?>> classSet = new ClassScanner().getClasses(packPath, true);
            for (Class<?> clazz : classSet) {
                NotInUse niu = clazz.getAnnotation(NotInUse.class);
                if (niu != null) {
                    continue;
                }
                if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                if (ActivityHandler.class.isAssignableFrom(clazz)) {
                    Activity actAnno = clazz.getAnnotation(Activity.class);
                    if (actAnno != null && actAnno.relatedFuncIds() != null) {
                        for (int funcId : actAnno.relatedFuncIds()) {
                            if (funcIdToHandlerMap.containsKey(funcId)) {
                                App.context.shutdownForce("活动重复注册的功能ID! funcId=" + funcId);
                            }
                            log.info("[ActivityLoader] 加载了一个活动功能 功能ID={} 处理类={}", funcId, clazz.getName());
                            funcIdToHandlerMap.put(funcId, clazz);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("加载活动处理类失败, e=", e);
        }
    }

    /**
     * 所有活动功能ID
     */
    public Set<Integer> allActivityFuncIds() {
        return new HashSet<>(funcIdToHandlerMap.keySet());
    }

    /**
     * 根据功能ID构建活动处理类
     *
     * @param funcId 功能ID
     */
    public ActivityHandler<?, ?> build(int funcId) {
        if (!funcIdToHandlerMap.containsKey(funcId)) {
            return null;
        }
        Class<?> clazz = funcIdToHandlerMap.get(funcId);
        try {
            return (ActivityHandler<?, ?>) clazz.newInstance();
        } catch (Exception e) {
            return null;
        }
    }
}
